package com.cah.game;

import org.json.JSONException;
import org.json.JSONObject;

import com.cah.library.UserFunctions;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class CreateGameFragment extends Fragment
{
	private String userKey;
	EditText gameNameField;
	Spinner numberOfPlayersSpinner;
	Button createButton;
	MainActivity main;
	
	public void onActivityCreated(Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		main = (MainActivity) getActivity();
		userKey = main.getUserKey();
		gameNameField = (EditText)main.findViewById(R.id.new_game_name);
		numberOfPlayersSpinner = (Spinner)main.findViewById(R.id.spinner_num_players);
		createButton = (Button)main.findViewById(R.id.createButton);
		main.setTitle("Create New Game");
		main.actionBar.setDisplayHomeAsUpEnabled(true);
		this.setRetainInstance(true);
		
		main.historyBackVisible = false;
		main.historyForwardVisible = false;
		main.invalidateOptionsMenu();
		
		createButton.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View arg0)
			{
				String gameName = gameNameField.getText().toString();
				String numOfPlayers = numberOfPlayersSpinner.getSelectedItem().toString();
				
				if(gameName.length()>0)
				{
					new CreateGameProcess().execute(gameName, numOfPlayers);
				}
				else
				{
					Toast.makeText(main, "Must enter a game name", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	
	
	private class CreateGameProcess extends AsyncTask<String, Void, JSONObject>
	{
		ProgressDialog pdia;
		@Override
		protected void onPreExecute()
		{
			pdia = new ProgressDialog(main);
			pdia.setMessage("Creating game...");
			pdia.show();
		}
		@Override
		protected JSONObject doInBackground(String... params)
		{
			String gameName = params[0];
			int numOfPlayers = Integer.parseInt(params[1]);
			UserFunctions uf = new UserFunctions(userKey);
			return uf.createGame(gameName, numOfPlayers);
		}
		
		protected void onPostExecute(JSONObject json)
		{
			try
			{
				if(json.getInt("success")==1)
				{
					Toast.makeText(main, "Game has been created!", Toast.LENGTH_SHORT).show();
					main.startLobbyFragment();
				}
				else
				{
					Toast.makeText(main, "Something went wrong!", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			pdia.dismiss();
		}
		
	}



	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		
		return inflater.inflate(R.layout.create_game, container, false);
	}
}
